<?php

namespace addons\shopro\controller\wm;

use addons\shopro\exception\Exception;
use think\Db;
use addons\shopro\controller\Base as AddonsBase;
class Job extends AddonsBase
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 团长。商家 个人中心 资金统计
     * 王猛 2022-2-17 22:18:30
     */
    function doYunSutuan2022(){
        set_time_limit(1200);

        // if($_SERVER['REMOTE_ADDR']!=='47.96.120.48') return 'Byebye!';
        //查询所有需要核算的订单

        $order_items = db('shopro_order_item')
            ->alias('a')
            ->join('shopro_user_store b','a.store_id=b.store_id')
            ->join('shopro_order c','c.id=a.order_id')
            ->where(['a.moneytime'=>date('Y-m-d'),'a.domoneytime'=>NULL,'a.refund_status'=>0])
            ->field('a.id,c.ext as order_ext,a.order_id,a.activity_type,a.goods_id,a.activity_id,a.need_domoney,b.user_id as store_user_id,a.user_id as order_user_id,a.activity_id,a.pay_price,c.ext,c.order_sn')
            ->select();
        // halt($order_items);
        if(empty($order_items)){
            self::log('无order_item','over！');
            return;
        } 
        
        $config_sj = config('site.config_sj');
        $config_zt_num = config('site.config_zt_num');
        foreach ($order_items as $order_item){

            $money_sj_count = number_format($order_item['pay_price']*$config_sj*0.01, 2);
            $store_id = db('shopro_goods')->where(['id'=>$order_item['goods_id']])->value('shopro_store_id');
            //遍历插入钱包表日志表跟修改用户余额，fast系统余额变更表【暂时不做】2张表
            //第一步:-------------------商家费用操作-------------------
            //商家费用结算给商家
            $money_sj = [
                'user_id'=>$order_item['store_user_id'],
                'wallet'=>$money_sj_count,
                'wallet_type'=>'money',
                'type'=>'xt',
                'item_id'=>$order_item['id'],
                'memo'=>'商家营收',
                'ext'=>json_encode(['order_id'=>$order_item['order_id'],'order_sn'=> $order_item['order_sn'],'order_item'=>$order_item['id']],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                'oper_type'=>'system',
                'oper_id'=>0,
                'wm_types'=>'sj',
                'store_id' => $store_id
            ];
            $this->doOne([$money_sj], 'sj');
            $update['sj_domoneytime']=time();
            $update['money_sj']=$money_sj_count; //商家费用
            $all_tuanzhang_money = 0; //1-3层团长佣金
            $money_zt_count = 0;  //被绑定的团长佣金
 
            //第二步:-------------------团长费用操作-------------------
            //开团结算给团长，以及绑定团员给上级团长
            $ext_arr = json_decode($order_item['ext'],true);
            $order_ext_arr = json_decode($order_item['order_ext'],true);
            $extend = false;
            if(isset($order_ext_arr['groupon_id'])){
                $extend = true;
               
            }
          
            if($order_item['need_domoney']=='1'&& $extend && isset($ext_arr['groupon_id'])){
                $groupon_id = $ext_arr['groupon_id'];
                $group_curr = $this->getNewGroup($groupon_id);
                foreach ($group_curr as $k=>$v){
                    if($group_curr[$k]['user_id']==$order_item['order_user_id']) unset($group_curr[$k]);
                }

                if(!empty($group_curr)){
                    foreach ($group_curr as &$v){
                        if($v['commission_type']=='1'){
                            $v['wallet'] = number_format($v['commission_money'], 2);
                        }else{
                            $v['wallet'] = number_format($v['cur_per'] * $order_item['pay_price']*0.01, 2);
                        }
                        $update['money_pt'.$v['level']]=$v['wallet'];
                        $all_tuanzhang_money+=$v['wallet'];
                        $v['wallet_type'] = 'money';
                        $v['oper_type'] = 'user';
                        $v['type'] = 'xt';
                        $v['item_id'] = $order_item['id'];
                        $v['memo'] = '开团佣金【'.$v['level'].'级团】';
                        $v['ext'] = json_encode(['order_id'=>$order_item['order_id'],'order_sn'=> $order_item['order_sn'],'order_item'=>$order_item['id']],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
                        $v['oper_id'] = 0;
                        $v['wm_types'] = 'pt';
                        $v['store_id'] = $store_id;
                    }
                    $this->doOne($group_curr,'pt');

                    $update['pt_domoneytime']=time();
                }
            }
            $update['domoneytime']=time();

            //第三步:-------------------订单会员的绑定团长佣金-------------------
            if(config('site.config_zt')=='1'){
                //被绑定的团长
                $money_zt_count = number_format($order_item['pay_price']*$config_zt_num*0.01, 2);
                $bind_user_id = db('user')->where(['id'=>$order_item['order_user_id']])->value('parent_user_id');
                if($bind_user_id){
                    $data_bind = [
                        'user_id' => $bind_user_id,
                        'wallet' => $money_zt_count,
                        'wallet_type' => 'money',
                        'oper_type' => 'user',
                        'type' => 'xt',
                        'item_id' => $order_item['id'],
                        'memo' => '绑定团长佣金',
                        'ext' => json_encode(['order_id'=>$order_item['order_id'],'order_sn'=> $order_item['order_sn'],'order_item'=>$order_item['id']],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                        'oper_id' => '0',
                        'wm_types' => 'pt',
                        'store_id' => $store_id
                    ];
                    $this->doOne([$data_bind],'pt');
                    $update['money_pt']=$money_zt_count;
                    $update['bind_domoneytime']=time();
                }
            }

            //第四步:-------------------平台的佣金-------------------
            $pingtai_money = $order_item['pay_price'] - $money_sj_count - $money_zt_count - $all_tuanzhang_money;
            $data_pingtai_money = [
                'wallet' => $pingtai_money,
                'user_id' => 1,
                'wallet_type' => 'money',
                'oper_type' => 'system',
                'type' => 'xt',
                'item_id' => $order_item['id'],
                'memo' => '平台官方佣金',
                'ext' => json_encode(['order_id'=>$order_item['order_id'],'order_sn'=> $order_item['order_sn'],'order_item'=>$order_item['id']],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                'oper_id' => '0',
                'wm_types' => 'yst',
                'store_id' => $store_id
            ];
            $this->doOne([$data_pingtai_money],'yst');
            $update['money_sys']=$pingtai_money;
            $update['sys_domoneytime']=time();

            //第五步:-------------------更新当前数据状态-------------------
            
            $update['need_domoney']='2';

            // halt($update);
            
            try{
                db('shopro_order_item')->where(['id'=>$order_item['id']])->update($update);
                self::log(['INFO'=>'结算完成','order_item_id'=>$order_item['id']],$order_item['id'].'-order_item_id数据结算- 【完成】');
            }catch (\think\Exception $e ){
                self::log(json_encode($e->getMessage(),JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),$order_item['id'].'-order_item_id数据结算- 【异常】');
            }
        }
    }

    //获取应该返给的团长 1-3层
    private function getNewGroup($id){
        $arr = [];
        try{
            //团详情
            $res_group = db('shopro_activity_groupon')->where(['id'=>$id])->field('id,user_id,order_top_groupon_id,order_superior_groupon_id')->find();
            if(empty($res_group)) return $arr;
            $superior_groupon_id = 0;//上级团id
            $order_top_groupon_id = 0;//顶级级团id
            if(!$res_group['order_top_groupon_id']){//无顶团团id 顶团团id为当前团id
                $order_top_groupon_id = $res_group['id'];
            }else{
                $superior_groupon_id = $res_group['order_superior_groupon_id'];
                $order_top_groupon_id = $res_group['order_top_groupon_id'];
            }

            //获取当前团的团长等级信息
            $identity_group = db('shopro_group_identity')
                ->where(['user_id'=>$res_group['user_id'],'activity_groupon_id'=>$order_top_groupon_id,'parent_groupon_id'=>$superior_groupon_id])
                ->field('id,user_id,level,parent_groupon_id,commission_type,commission_money,commission_bili')->find();
            if(empty($identity_group)) return $arr;
            $identity_group = $this->getCurPer($identity_group);
            $arr[] = $identity_group;
            switch ($identity_group['level']){
                case '1'://大团长、
                    break;
                case '2'://小团长  往上再找一级、
                    //大团长身份等级信息
                    $res_group_one = db('shopro_activity_groupon')
                        ->where(['id'=>$identity_group['parent_groupon_id']])
                        ->field('id,user_id,order_top_groupon_id,order_superior_groupon_id')->find();
                    if(empty($res_group_one)) return $arr;
                    $identity_group_one = db('shopro_group_identity')
                        ->where(['user_id'=>$res_group_one['user_id'],'activity_groupon_id'=>$res_group_one['id'],'parent_groupon_id'=>0])
                        ->field('id,user_id,level,parent_groupon_id,commission_type,commission_money,commission_bili')->find();
                    if(empty($identity_group_one)) return $arr;
                    $identity_group_one = $this->getCurPer($identity_group_one);
                    $identity_group_one['cur_per']= $identity_group_one['cur_per']-$identity_group['cur_per'];
                    $arr[] = $identity_group_one;
                    break;
                case '3'://小小团长 往上再找二级
                    //小团长开的团详情
                    $res_group_one = db('shopro_activity_groupon')
                        ->where(['id'=>$identity_group['parent_groupon_id']])
                        ->field('id,user_id,order_top_groupon_id,order_superior_groupon_id')->find();
                    if(empty($res_group_one)) return $arr;
                    //小团长身份等级信息
                    $identity_group_one = db('shopro_group_identity')
                        ->where(['user_id'=>$res_group_one['user_id'],'activity_groupon_id'=>$res_group_one['order_top_groupon_id'],'parent_groupon_id'=>$res_group_one['order_superior_groupon_id']])
                        ->field('id,user_id,level,parent_groupon_id,commission_type,commission_money,commission_bili')->find();
                    if(empty($identity_group_one)) return $arr;
                    $identity_group_one = $this->getCurPer($identity_group_one);
                    $identity_group_one['cur_per']= $identity_group_one['cur_per']-$identity_group['cur_per'];
                    //大团长身份等级信息

                    $res_group_two = db('shopro_activity_groupon')
                        ->where(['id'=>$identity_group_one['parent_groupon_id']])
                        ->field('id,user_id,order_top_groupon_id,order_superior_groupon_id')->find();
                    if(empty($res_group_two)) return $arr;
                    $identity_group_two = db('shopro_group_identity')
                        ->where(['user_id'=>$res_group_two['user_id'],'activity_groupon_id'=>$res_group_two['id'],'parent_groupon_id'=>0])
                        ->field('id,user_id,level,parent_groupon_id,commission_type,commission_money,commission_bili')->find();
                    if(empty($identity_group_two)) return $arr;
                    $identity_group_two = $this->getCurPer($identity_group_two);
                    $identity_group_two['cur_per']=$identity_group_two['cur_per']- $identity_group_one['cur_per']-$identity_group['cur_per'];
                    $arr[] = $identity_group_one;
                    $arr[] = $identity_group_two;
                    break;
            } 
        }catch (\think\Exception $e ){
            self::log(json_encode($e->getMessage(),JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),$id.'-groupon_id——获取1-3团长数据结算-error:');
        }finally{
            return $arr;
        }
    }

    private static function log($data,$str){
        $file = 'log/'.date('Ymd').'.log';
        if(!file_exists($file)){
            fopen($file, "a");
        }
        file_put_contents($file,date('Y-m-d H:i:s---').$str.'---'. json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
    }

    //单条余额修改、单条钱包逻辑
    private function doOne($datas, $type){
//        halt($datas);
        foreach ($datas as $data){
            Db::startTrans();
            try {
                $user = model('app\common\model\User')->get($data['user_id']);
                if ($user && $data['wallet'] != 0) {
                    $before = $user->money;
                    $after = function_exists('bcadd') ? bcadd($user->money, $data['wallet'], 2) : $user->money + $data['wallet'];
                    //更新会员信息
                    $user->save(['money' => $after]);
                    //写入日志 \addons\shopro\model\UserWalletLog
                    model('\addons\shopro\model\UserWalletLog')->create([
                        'user_id' => $data['user_id'],
                        'wallet_type'=>$data['wallet_type'],
                        'wallet'=>$data['wallet'],
                        'type'=>$data['type'],
                        'before'=>$before,
                        'after'=>$after,
                        'item_id'=>$data['item_id'],
                        'memo'=>$data['memo'],
                        'ext'=>$data['ext'],
                        'oper_type'=>$data['oper_type'],
                        'oper_id'=>$data['oper_id'],
                        'createtime'=>time(),
                        'updatetime'=>time(),
                        'wm_types'=>$data['wm_types'],
                        'is_refund'=>$data['is_refund']??'0',
                        'store_id'=>$data['store_id']??'0',
                    ]);
                }
                self::log(json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),$type.'结算-正常:');
                Db::commit();
            }catch (\Exception $e) {
                self::log(json_encode($e->getMessage(),JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),$type.'异常结算-error:');
                Db::rollback();
            }
        }
        return true;
    }


    private function getCurPer($data){
        if($data['commission_type']=='1'){
            $data['cur_per'] = $data['commission_money'];
        }else{
            $data['cur_per'] =  $data['commission_bili'];
        }
        return $data;
    }

    private function getIp(){
        if ($_SERVER["HTTP_CLIENT_IP"] && strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown")) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            if ($_SERVER["HTTP_X_FORWARDED_FOR"] && strcasecmp($_SERVER["HTTP_X_FORWARDED_FOR"], "unknown")) {
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else {
                if ($_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER["REMOTE_ADDR"], "unknown")) {
                    $ip = $_SERVER["REMOTE_ADDR"];
                } else {
                    if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],
                            "unknown")
                    ) {
                        $ip = $_SERVER['REMOTE_ADDR'];
                    } else {
                        $ip = "unknown";
                    }
                }
            }
        }
        return ($ip);
    }


    /**
     * 王猛 2022-2-4 23:15:19
     * 仅退款逻辑
     * @param $item_id 退款项id
     */
    function backMoney($item_id=54){
        //查询是否有分佣记录
        $refund_status = db('shopro_order_item')->where(['id'=>$item_id])->value('refund_status');
        if($refund_status==2) return ;
        $items = db('shopro_user_wallet_log')->where(['item_id'=>$item_id,'is_refund'=>0,'type'=>'xt','wallet_type'=>'money'])->select();
//        halt($items);
        if(!empty($items)){
            foreach ($items as $item){
                $data = [
                    'user_id' => $item['user_id'],
                    'wallet' =>  -$item['wallet'],
                    'wallet_type' =>  $item['wallet_type'],
                    'oper_type' =>  $item['oper_type'],
                    'type' =>  $item['type'],
                    'item_id' =>  $item['item_id'],
                    'memo' =>  '费用扣回【退单】',
                    'ext' =>  $item['ext'],
                    'oper_id' =>  $item['oper_id'],
                    'wm_types' =>  $item['wm_types'],
                    'is_refund' =>  '1',
                    'store_id' =>  $item['store_id'],
                ];
                $this->doOne([$data],'退款'.$item['wm_types']);
            }

            return ;
        }
    }


}